//
//  PublishTextController.m
//  collection
//
//  Created by 靖 张 on 12/13/11.
//  Copyright (c) 2011 Tsinghua University. All rights reserved.
//

#import "PublishTextController.h"
#import "CollectionDataManager.h"
#import "TagInfo.h"
#import "MBProgressHUDHelper.h"
#import <QuartzCore/QuartzCore.h>

@interface PublishTextController()

@property (nonatomic, strong) IBOutlet  UIImageView*    titleBgPic;
@property (retain, nonatomic) IBOutlet UIScrollView *pictureContainer;
@property (nonatomic, strong) IBOutlet  UITextView* editView;
@property (retain, nonatomic) IBOutlet UILabel *textCountIndicatorLabel;
@property (nonatomic, strong) IBOutlet  UIView*     tagHintBar;
@property (nonatomic, strong) IBOutlet  UIView*     tagSelectorView;
@property (retain, nonatomic) IBOutlet UIImageView *textFrameView;
@property (retain, nonatomic) IBOutlet UIImageView *separatorView;

@property (nonatomic, retain) MBProgressHUD* postResultIndicatorView;

@property (nonatomic, strong)   NSMutableArray*     pictureArray;
@property (nonatomic, retain)   NSMutableArray*       tagArray;

- (IBAction)onClickSendButton:(id)sender;
- (IBAction)onClickCancelButton:(id)sender;
- (void)onClickTagIndicatorView:(id)sender;
- (void)onClickAddPicture:(id)sender;
- (void)onClickDelPicture:(id)sender;
- (void)onClickTagItem:(id)sender;
- (void)onTapThisView:(id)sender;
- (void)dismissKeyboard:(id)sender;
- (void)animateView:(NSInteger)moveUpHeight;
- (BOOL)checkPostContent;

@end

@implementation PublishTextController

@synthesize isPicture   = _isPicture;
@synthesize titleBgPic  = _titleBgPic;
@synthesize pictureContainer = _pictureContainer;
@synthesize editView        = _editView;
@synthesize textCountIndicatorLabel = _textCountIndicatorLabel;
@synthesize tagHintBar      = _tagHintBar;
@synthesize tagSelectorView = _tagSelectorView;
@synthesize textFrameView = _textFrameView;
@synthesize separatorView = _separatorView;

@synthesize postResultIndicatorView = _postResultIndicatorView;
@synthesize pictureArray    = _pictureArray;
@synthesize tagArray = _tagArray;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    self.pictureContainer = nil;
    self.editView = nil;
    self.tagHintBar = nil;
    self.tagSelectorView = nil;
    self.pictureArray = nil;
    self.tagArray = nil;
    self.postResultIndicatorView = nil;
    
    [_textFrameView release];
    [_separatorView release];
    [_textCountIndicatorLabel release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"all_bg"]];
    
    // Text mode
    if (!self.isPicture) {
        
        self.titleBgPic.image = [UIImage imageNamed:@"top_releaseword_on"];
        self.pictureContainer.hidden = YES;
        self.separatorView.hidden = YES;
        self.textFrameView.hidden = YES;
        
        CGRect frame;
        frame = self.tagSelectorView.frame;
        frame.origin.y = self.view.frame.size.height - frame.size.height;
        self.tagSelectorView.frame = frame;
        
        frame = self.tagHintBar.frame;
        frame.origin.y = self.tagSelectorView.frame.origin.y - frame.size.height;
        self.tagHintBar.frame = frame;
        self.tagHintBar.backgroundColor = [UIColor colorWithRed:136./255. green:136./255. blue:136./255. alpha:1];
        UIImageView* tagIndicatorView = (UIImageView*)[self.tagHintBar viewWithTag:1];
        tagIndicatorView.image = [UIImage imageNamed:@"ico_tag16_w"];
        
        UILabel* tagLabel = (UILabel*)[self.tagHintBar viewWithTag:2];
        tagLabel.textColor = [UIColor whiteColor];
        
        UILabel* tagLabelValues = (UILabel*)[self.tagHintBar viewWithTag:3];
        tagLabelValues.textColor = [UIColor whiteColor];
        
        frame = self.editView.frame;
        frame.origin.x = 0;
        frame.origin.y = 44;
        frame.size.width = 320;
        frame.size.height = self.tagHintBar.frame.origin.y;
        self.editView.frame = frame;
        
        frame = self.textCountIndicatorLabel.frame;
        frame.origin.x = self.editView.frame.origin.x + self.editView.frame.size.width - self.textCountIndicatorLabel.frame.size.width;
        frame.origin.y = self.editView.frame.origin.y + self.editView.frame.size.height - self.textCountIndicatorLabel.frame.size.height;
        self.textCountIndicatorLabel.frame = frame;
        
        [self.editView becomeFirstResponder];
        
        frame = self.textCountIndicatorLabel.frame;
        frame.origin.x = self.editView.frame.origin.x + self.editView.frame.size.width - frame.size.width - 10;
        frame.origin.y = self.editView.frame.origin.y + self.editView.frame.size.height - frame.size.height;
        self.textCountIndicatorLabel.frame = frame;
    }
    // Picture mode
    else {
        self.titleBgPic.image = [UIImage imageNamed:@"top_releasepic_on"];
        UIButton* imageActionView = (UIButton*)[self.pictureContainer viewWithTag:11];
        
        UIImageView* tagIndicatorView = (UIImageView*)[self.tagHintBar viewWithTag:1];
        tagIndicatorView.image = [UIImage imageNamed:@"ico_tag16_g"];
        
        [imageActionView addTarget:self action:@selector(onClickAddPicture:) forControlEvents:UIControlEventTouchUpInside];
        
        self.pictureArray = [NSMutableArray array];
    }
    
    UITapGestureRecognizer* clickTagIndicatorViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickTagIndicatorView:)];
    clickTagIndicatorViewGesture.numberOfTapsRequired = 1;
    [self.tagHintBar addGestureRecognizer:clickTagIndicatorViewGesture];
    [clickTagIndicatorViewGesture release];
    
    self.tagArray = [NSMutableArray array];
    
    // Tag selector view, add tags
    CollectionDataManager* dataManager = [CollectionDataManager sharedInstance];
    NSArray* hotTags = dataManager.hotTagList;
    int xRange = 0;
    for (int i = 0; i < [hotTags count]; i++) {
        TagInfo* tag = [hotTags objectAtIndex:i];
        
        int lineIndex = i / 4;
        int colIndex = i % 4;
        
        // Add tags to tag selector view
        UIImage* buttonBgImg = [[UIImage imageNamed:@"tag_btn"] stretchableImageWithLeftCapWidth:8 topCapHeight:5];
        
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];//[[UIButton alloc] init];
        [button setBackgroundImage:buttonBgImg forState:UIControlStateNormal];
        UIFont* font = [UIFont systemFontOfSize:12.0f];
        button.titleLabel.font = font;
        button.titleEdgeInsets = UIEdgeInsetsMake(3, 5, 3, 5);
        [button setTitleColor:[UIColor colorWithRed:51./255. green:51./255. blue:51./255. alpha:1] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRed:153./255. green:153./255. blue:153./255. alpha:1] forState:UIControlStateSelected];
        [button setTitle:tag.name forState:UIControlStateNormal];
        [button setTitle:tag.name forState:UIControlStateSelected];
        [button addTarget:self action:@selector(onClickTagItem:) forControlEvents:UIControlEventTouchUpInside];
        button.selected = NO;
        button.adjustsImageWhenHighlighted = NO;
        button.tag = 10 + i;
        
        CGSize size = CGSizeMake(320,2000);
        CGSize buttonSize = [tag.name sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
        
        CGRect frame;
        frame.size = CGSizeMake(buttonSize.width + 25, buttonSize.height + 15);
        frame.origin.x = xRange + 10;
        frame.origin.y = 10 + lineIndex * (buttonSize.height + 15 + 8);
        button.frame = frame;
        
        xRange = frame.origin.x + frame.size.width;
        if (colIndex == 3) {
            xRange = 0;
        }
        
        [self.tagSelectorView addSubview:button];
    }
}

- (void)viewDidUnload
{
    [self setPictureContainer:nil];
    [self setTextFrameView:nil];
    [self setSeparatorView:nil];
    [self setTextCountIndicatorLabel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.editView = nil;
    self.tagHintBar = nil;
    self.tagSelectorView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - [UITextViewDelegate]

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
/*
    if (self.isPicture) {
        
        CGFloat aim = 460 - self.editView.inputAccessoryView.superview.frame.size.height;
        CGFloat curHeight = self.editView.frame.origin.y + self.editView.frame.size.height;
        
        if (curHeight > aim) {
            [self animateView:(curHeight - aim)];
        }
    }
    else {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3f];
        CGRect frame = self.textCountIndicatorLabel.frame;
        frame.origin.y = 460 - self.editView.inputAccessoryView.superview.frame.size.height - self.textCountIndicatorLabel.frame.size.height;
        self.textCountIndicatorLabel.frame = frame;
        [UIView commitAnimations];
    }
*/
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    
    if (!self.isPicture) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3f];
        CGRect frame = self.textCountIndicatorLabel.frame;
        frame.origin.y = 270;//self.editView.frame.origin.y + self.editView.frame.size.height - self.textCountIndicatorLabel.frame.size.height;
        self.textCountIndicatorLabel.frame = frame;
        
        frame = self.editView.frame;
        [UIView commitAnimations];
    }
}

- (void)textViewDidChange:(UITextView *)textView {
    
    int textCount = 140 - textView.text.length;
    self.textCountIndicatorLabel.text = [NSString stringWithFormat:@"%d", textCount];
    
    if (textCount < 0) {
        self.textCountIndicatorLabel.textColor = [UIColor redColor];
    }
    else {
        self.textCountIndicatorLabel.textColor = [UIColor blackColor];
    }
}

#pragma mark - [UIActionSheetDelegate]

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    //- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    }
    
    int tag = actionSheet.tag;
    // Add picture
    if (tag == 11) {
        UIImagePickerControllerSourceType sourceType;
        if (buttonIndex == 0) {
            sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        else if (buttonIndex == 1) {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        
        UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        [self presentModalViewController:imagePickerController animated:YES];
        [imagePickerController release];
    }
    
    // Cancel publishment
    else if (tag == 100) {
        if (buttonIndex == actionSheet.destructiveButtonIndex) {
            [self dismissModalViewControllerAnimated:YES];
        }
    }
    
    // Remove picture
    else {
        if (buttonIndex == actionSheet.destructiveButtonIndex) {
            
            // Remove this image
            UIButton* imageView = (UIButton*)[self.pictureContainer viewWithTag:tag];
            UIImage* btnImg = [imageView backgroundImageForState:UIControlStateNormal];
            for (UIImage* img in self.pictureArray) {
                if (img == btnImg) {
                    [self.pictureArray removeObject:img];
                    break;
                }
            }
            
            [imageView removeFromSuperview];
            
            // Move the right images and change their tags
            for (int t = tag + 1; t < 25; t++) {
                UIImageView* imageView = (UIImageView*)[self.pictureContainer viewWithTag:t];
                CGRect frame = imageView.frame;
                frame.origin.x -= 90;
                imageView.frame = frame;
                //Change tag
                imageView.tag--;
            }
            
            // Update action image and available count label
            UIButton* imageActionView = (UIButton*)[self.pictureContainer viewWithTag:11];
            UILabel* availableImageLabel = (UILabel*)[self.pictureContainer viewWithTag:12];
            CGRect frame = imageActionView.frame;
            frame.origin.x -= 90;
            imageActionView.frame = frame;
            imageActionView.hidden = NO;
            
            availableImageLabel.text = [NSString stringWithFormat:@"%d", 5 - [self.pictureArray count]];
            frame = availableImageLabel.frame;
            frame.origin.x -= 90;
            availableImageLabel.frame = frame;
            availableImageLabel.hidden = NO;
            
            // Adjust the content size
            if ([self.pictureArray count] == 0) {
                UILabel* hintLabel = (UILabel*)[self.pictureContainer viewWithTag:13];
                hintLabel.hidden = NO;
                
                CGSize size = self.pictureContainer.contentSize;
                size.width = 320;
                self.pictureContainer.contentSize = size;
            }
            else {
                int rightEdge = imageActionView.frame.origin.x + imageActionView.frame.size.width + 15;
                int width = (rightEdge > 320) ? rightEdge : 320;
                CGSize size = self.pictureContainer.contentSize;
                size.width = width;
                self.pictureContainer.contentSize = size;
            }
        }
    }
}

#pragma mark - [UIImagePickerControllerDelegate]

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage* editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
    if (editedImage != nil) {
        // Hide the hint text
        UILabel* hintLabel = (UILabel*)[self.pictureContainer viewWithTag:13];
        hintLabel.hidden = YES;
        
        // Add Image icon
        int picCount = [self.pictureArray count];
        
        UIButton* newPicView = [UIButton buttonWithType:UIButtonTypeCustom];
        newPicView.frame = CGRectMake(picCount * 90 + 15, 15, 75, 75);
        newPicView.tag = 20 + picCount;
        [newPicView setBackgroundImage:editedImage forState:UIControlStateNormal];
        [newPicView addTarget:self action:@selector(onClickDelPicture:) forControlEvents:UIControlEventTouchUpInside];
        newPicView.layer.masksToBounds = YES;
        newPicView.layer.cornerRadius = 5;
        
        
        [self.pictureContainer addSubview:newPicView];
        
        [self.pictureArray addObject:editedImage];
        
        // Adjust the action image and available count label
        UIButton* imageActionView = (UIButton*)[self.pictureContainer viewWithTag:11];
        UILabel* availableImageLabel = (UILabel*)[self.pictureContainer viewWithTag:12];
        
        CGRect frame = imageActionView.frame;
        frame.origin.x += 90;
        imageActionView.frame = frame;
        
        availableImageLabel.text = [NSString stringWithFormat:@"%d", 5 - [self.pictureArray count]];
        frame = availableImageLabel.frame;
        frame.origin.x += 90;
        availableImageLabel.frame = frame;
        
        // Adjust the scroll content size
        if ([self.pictureArray count] == 5) {
            imageActionView.hidden = YES;
            availableImageLabel.hidden = YES;
            
            int rightEdge = newPicView.frame.origin.x + newPicView.frame.size.width + 15;
            int width = (rightEdge > 320) ? rightEdge : 320;
            CGSize size = self.pictureContainer.contentSize;
            size.width = width;
            self.pictureContainer.contentSize = size;
        }
        else {      
            int rightEdge = imageActionView.frame.origin.x + imageActionView.frame.size.width + 15;
            int width = (rightEdge > 320) ? rightEdge : 320;
            CGSize size = self.pictureContainer.contentSize;
            size.width = width;
            self.pictureContainer.contentSize = size;
            
            // Scroll to make action view visible in the screen
            if (rightEdge > 320) {
                [self.pictureContainer setContentOffset:CGPointMake(rightEdge - 320, 0) animated:YES];
            }
        }
        
        //    [newPicView release];
    }
    
    [picker dismissModalViewControllerAnimated:YES];
}

#pragma mark - [UIAlertViewDelegate]

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == alertView.firstOtherButtonIndex) {
        [self dismissModalViewControllerAnimated:YES];
    }
}

#pragma mark - Private methods

- (void)animateView:(NSInteger)moveUpHeight
{
    CGRect rect = self.view.frame;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    
    //    if (moveUpHeight > 0) 
    {
        rect.origin.y -= moveUpHeight;
    }
    
    self.view.frame = rect;
    [UIView commitAnimations];
}

- (IBAction)onClickSendButton:(id)sender {
    
    // 检查内容是否符合要求
    if (![self checkPostContent]) {
        return;
    }
    
    CollectionDataManager* dataManager = [CollectionDataManager sharedInstance];
    UserInfo* myself = dataManager.currentLoginUser;
    
    Feed* newFeed = [[Feed alloc] init];
    static long long ID = 100ll;
    newFeed.feedID = ID++;
    
    newFeed.feedType = FeedType_Original;
    newFeed.userID = myself.userID;
    newFeed.nickname = myself.nickname;
    newFeed.avatarURL = myself.avatarURL;
    newFeed.avatar = myself.avatar;
    
    if (![self.editView.text isEqualToString:@""]) {
        newFeed.text = self.editView.text;
    }
    
    newFeed.pictures = self.pictureArray;
    newFeed.tags = self.tagArray;    
    newFeed.originalFeed = nil;
    newFeed.publishTime = [NSDate date];
    
    [dataManager addFeed:newFeed];
    [newFeed release];
   
    [self.editView resignFirstResponder];
    if (self.postResultIndicatorView == nil) {
        self.postResultIndicatorView = [MBProgressHUDHelper popUpMBProcessHUD:self.view delegate:nil];
        [self.postResultIndicatorView show:YES];
    //    self.postResultIndicatorView.labelText = @"正在发送...";
     
        [self performSelector:@selector(postResult:) withObject:self afterDelay:1.5f];
    }
}

- (void)postResult:(BOOL)result {
    
    [MBProgressHUDHelper changeToMBSuccessMode:self.postResultIndicatorView customMsg:@"发布成功!" afterDelay:1.0f];
    [self performSelector:@selector(close) withObject:self afterDelay:1.0f];
}

- (void)close {
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)onClickCancelButton:(id)sender {
    
    // 如果没有内容，直接关闭发布页面
    if (self.isPicture) {
        if (self.pictureArray.count == 0) {
            [self dismissModalViewControllerAnimated:YES];
            
            return;
        }
    }
    else {
        if ([self.editView.text isEqualToString:@""]) {
            [self dismissModalViewControllerAnimated:YES];
            
            return;
        }
    }
    
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"已添加内容，是否放弃" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"确认放弃" otherButtonTitles:nil];
    actionSheet.tag = 100;
    [actionSheet showInView:self.view];
    [actionSheet release];
}

- (void)onClickTagIndicatorView:(id)sender {
    
    [self.editView resignFirstResponder];
}

- (void)onClickAddPicture:(id)sender {
    
    UIButton* btn = (UIButton*)sender;
    if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:imagePickerController animated:YES];
        [imagePickerController release];
        return;
    }
    
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                                             delegate:self
                                                    cancelButtonTitle:@"Cancel!"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"相册选择", nil];
    actionSheet.tag = btn.tag;
    [actionSheet showInView:self.view];
    [actionSheet release];
}

- (void)onClickDelPicture:(id)sender {
    
    UIButton* btn = (UIButton*)sender;
    int index = btn.tag - 20;
    if (index < 0 || index > 4) {
        return;
    }
    
    UIActionSheet* delActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"删除" otherButtonTitles:nil];
    delActionSheet.tag = btn.tag;
    [delActionSheet showInView:self.view];
    [delActionSheet release];
}

- (void)onClickTagItem:(id)sender {
    
    UIButton* tagButton = (UIButton*)sender;
    if (tagButton.selected == NO) {
        UIImageView* selectedImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tag_choose"]];
        int tagNumber = tagButton.tag + 100;
        selectedImageView.tag = tagNumber;
        
        CGRect frame = tagButton.frame;
        CGSize imgSize = selectedImageView.image.size;
        CGRect imgFrame = CGRectMake(frame.origin.x + frame.size.width - imgSize.width / 2, frame.origin.y - imgSize.height / 3, imgSize.width * 0.8, imgSize.height * 0.8);
        selectedImageView.frame = imgFrame;
        
        [self.tagSelectorView addSubview:selectedImageView];
        [selectedImageView release];
        
        [UIView animateWithDuration:0.133f 
                         animations:^{
                             CGRect f1 = selectedImageView.frame;
                             f1.size.width = imgSize.width * 1.2;
                             f1.size.height = imgSize.height * 1.2;
                             selectedImageView.frame = f1;
                         } 
                         completion:^(BOOL finished) {
                             [UIView animateWithDuration:0.083f
                                              animations:^{
                                                  CGRect f2 = selectedImageView.frame;
                                                  f2.size.width = imgSize.width * 0.85;
                                                  f2.size.height = imgSize.height * 0.85;
                                                  selectedImageView.frame = f2;
                                              }
                                              completion:^(BOOL finished) {
                                                  [UIView animateWithDuration:0.053f
                                                                   animations:^{
                                                                       CGRect f3 = selectedImageView.frame;
                                                                       f3.size.width = imgSize.width;
                                                                       f3.size.height = imgSize.height;
                                                                       selectedImageView.frame = f3;
                                                                   }
                                                                   completion:^(BOOL finished) {
                                                                       
                                                                   }];
                                              }];
                         }];
        
        [self.tagArray addObject:tagButton.titleLabel.text];
        
        UILabel* tagListLabel = (UILabel*)[self.tagHintBar viewWithTag:3];
        tagListLabel.text = [NSString stringWithFormat:@"%@  %@", tagListLabel.text, tagButton.titleLabel.text];
        
        tagButton.selected = YES;
    }
    else {
        int tagNumber = tagButton.tag + 100;
        UIImageView* selectedImageView = (UIImageView*)[self.tagSelectorView viewWithTag:tagNumber];
        if (selectedImageView == nil) {
            return;
        }
        [selectedImageView removeFromSuperview];
        
        UILabel* tagListLabel = (UILabel*)[self.tagHintBar viewWithTag:3];
        NSString* text = tagListLabel.text;
        NSString* pattern = [NSString stringWithFormat:@"  %@", tagButton.currentTitle];
        
        [self.tagArray removeObject:tagButton.currentTitle];
        
        NSRange range = [text rangeOfString:pattern];
        tagListLabel.text = [text stringByReplacingCharactersInRange:range withString:@""];
        
        tagButton.selected = NO;
    }
}

- (void)onTapThisView:(id)sender {
    
    for (UIView* view in [self.view subviews]) {
        [view resignFirstResponder];
    }
}

- (void)dismissKeyboard:(id)sender {
    
    [self.editView resignFirstResponder];
    
    if (self.isPicture) {
        CGRect frame = self.view.frame;
        [self animateView:(frame.origin.y - 20)];
    }
}

- (BOOL)checkPostContent {
    
    NSString* alertText = nil;
    if (self.isPicture) {
        if (self.pictureArray.count == 0) {
            alertText = @"抱歉，需要添加图片才能发布。";
        }
        else if (self.editView.text.length > 140) {
            alertText = @"抱歉，最多输入140字";
        }
    }
    else {
        if ([self.editView.text isEqualToString:@""]) {
            alertText = @"抱歉，需要输入文字才能发布。";
        }
        else if (self.editView.text.length > 140) {
            alertText = @"抱歉，最多输入140字";
        }
    }
    
    if (alertText != nil) {
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:alertText delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        [alertView release];
        
        return NO;
    }
    
    return YES;
}

- (void)keyboardWillShow:(NSNotification *) notification {
    NSDictionary *info = [notification userInfo];
    
    NSValue* value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    
    if (self.isPicture) {
        int shiftUpOffset = keyboardSize.height - self.tagSelectorView.frame.size.height;
        [self animateView:shiftUpOffset];
    }
    else {
        [UIView animateWithDuration:0.3f animations:^() {
            CGRect frame = self.editView.frame;
            frame.size.height = self.view.frame.size.height - 44 - self.tagHintBar.frame.size.height - keyboardSize.height;
            self.editView.frame = frame;
            
            frame = self.textCountIndicatorLabel.frame;
            frame.origin.y = self.editView.frame.origin.y + self.editView.frame.size.height - frame.size.height;
            self.textCountIndicatorLabel.frame = frame;
            
            frame = self.tagHintBar.frame;
            frame.origin.y = self.editView.frame.origin.y + self.editView.frame.size.height;
            self.tagHintBar.frame = frame;
            
            frame = self.tagSelectorView.frame;
            frame.origin.y = self.tagHintBar.frame.origin.y + self.tagHintBar.frame.size.height;
            self.tagSelectorView.frame = frame;
        }];
    }
}

- (void)keyboardWillHide:(NSNotification *) notification {
    NSDictionary *info = [notification userInfo];
    
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    
    if (self.isPicture) {
        int shiftDownOffset = keyboardSize.height - self.tagSelectorView.frame.size.height;
        [self animateView:(-shiftDownOffset)];
    }
    else {
        [UIView animateWithDuration:0.3f animations:^() {
            CGRect frame = self.tagSelectorView.frame;
            frame.origin.y = self.view.frame.size.height - frame.size.height;
            self.tagSelectorView.frame = frame;
            
            frame = self.tagHintBar.frame;
            frame.origin.y = self.tagSelectorView.frame.origin.y - frame.size.height;
            self.tagHintBar.frame = frame;
            
            frame = self.editView.frame;
            frame.size.height = self.view.frame.size.height - 44 - self.tagHintBar.frame.size.height - self.tagSelectorView.frame.size.height;
            self.editView.frame = frame;
            
            frame = self.textCountIndicatorLabel.frame;
            frame.origin.y = self.tagHintBar.frame.origin.y - frame.size.height;
            self.textCountIndicatorLabel.frame = frame;
        }];
    }
}

@end
